﻿#region License
// Copyright (c) 2012 Mund Consulting Ltd
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using SharePoint.Foundation.Publishing.Controls;
using Microsoft.SharePoint.Utilities;



namespace SharePoint.Foundation.Publishing
{
    /// <summary>
    /// Responsible for managing the publishing FieldControls and saving the respective values.
    /// </summary>
    public class SPFPublishingPage : Microsoft.SharePoint.WebPartPages.WebPartPage
    {
        #region Constants

        private const string constDesign = "Design";
        private const string constPlaceHolderMain = "PlaceHolderMain";
        private const string constBtnText = "Save";
        private const string constTargetCtrl = "TargetControl";
        private const string constEventTarget = "__EVENTTARGET";
        private const string constSave = "ctl04";
        private const string constKeepEditSave = "ctl02";
        private const string constStop = "stop";
        private const string constFieldControlType = "ASP._controltemplates_sharepoint_foundation_publishing_editfieldcontrol_ascx";
        private const string constRibbonReadTab = "Ribbon.Read";
        private const string constRibbonWikiTab = "Ribbon.WikiPageTab";
        private const string constRibbonPublishTab = "Ribbon.PublishTab";
        private const string constRibbonWebPartPage = "Ribbon.WebPartPage";
        private const string constKeepEditQueryString = "?ControlMode=Edit&DisplayMode=Design";

        #endregion

        #region Event Handlers
       
        protected override void OnLoad(EventArgs e)
        {
            SPRibbon current = SPRibbon.GetCurrent(this.Page);
            if (current != null) //&& HttpContext.Current.User.Identity.IsAuthenticated)
            {
                this.Page.Controls.Add(new PageState());
                current.CommandUIVisible = true;
                current.MakeTabAvailable(constRibbonReadTab);
                current.MakeTabAvailable(constRibbonWikiTab);
                current.MakeTabAvailable(constRibbonPublishTab);
                current.TrimById(constRibbonWebPartPage);
            }
            if (HttpContext.Current.Request.Form[constEventTarget] == constSave)
            {
                this.LoadComplete += new EventHandler(Save);
            }
            else if (HttpContext.Current.Request.Form[constEventTarget] == constKeepEditSave)
            {
                this.LoadComplete += new EventHandler(Save);
            }
        }

        #endregion

        #region Methods
        /// <summary>
        /// Saves the FieldContorl's values to the respective fields.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Save(object sender, EventArgs e)
        {
            WebPartManager wpManager = WebPartManager.GetCurrentWebPartManager(Page);

            if (wpManager.DisplayMode == WebPartManager.DesignDisplayMode)
            {
                ContentPlaceHolder cphMain = (ContentPlaceHolder)this.Master.FindControl(constPlaceHolderMain);
                SPContext.Current.Web.AllowUnsafeUpdates = true;
                foreach (Control ctrl in cphMain.Controls)
                {
                    if (ctrl.GetType().ToString() == constFieldControlType)
                    {
                        try
                        {
                            EditFieldControl editFieldControl = (EditFieldControl)ctrl;
                            SPItem item = SPContext.Current.Item;
                            item[editFieldControl.FieldName] = editFieldControl.BaseControl.Value;
                            item.Update();
                        }
                        catch
                        {
                        }
                    }
                }
                SPContext.Current.Web.AllowUnsafeUpdates = false;
            }

            string url=HttpContext.Current.Request.Url.AbsolutePath;
            SPRedirectFlags flags = SPRedirectFlags.DoNotEncodeUrl;
            if (HttpContext.Current.Request.Form[constEventTarget] == constKeepEditSave)
            {
                url += constKeepEditQueryString;
            }
           
            SPUtility.Redirect(url, flags, HttpContext.Current);
        }

        #endregion
    }
}
